package com.shanpin.shebao.admin.module.user;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.alibaba.druid.sql.visitor.functions.Concat;
import com.shanpin.shebao.admin.db.AdminDbRepository;
import com.shanpin.shebao.admin.db.AppDbRepository;
import com.shanpin.shebao.admin.module.user.model.Company;
import com.shanpin.shebao.admin.module.user.model.Contract;
import com.shanpin.shebao.utility.MoreCriteria;
import com.shanpin.shebao.utility.PageModel;

@Repository
public class CompanyDao {

	private static final String QUERY_DETAIL_SQL = "SELECT company.* FROM t_ent_sign company";
	
	@Autowired
	private AppDbRepository app;
	@Autowired
	private AdminDbRepository admin;
	
	private int getTotalRecord(MoreCriteria c, String calledSql){
		Long count = 0L;
		String sql = "SELECT COUNT(1) FROM t_ent_sign company";
		sql = sql + c.getSqlString() + calledSql;
		count = app.queryLong(sql, c.getValueList().toArray());
		return count.intValue();
	}
	
	public PageModel queryPage(int pageNo, int pageSize, MoreCriteria c, String calledSql) {
		
		int start = (pageNo-1)*pageSize;
		
		String sql = QUERY_DETAIL_SQL;
		PageModel pm = new PageModel();
		
		sql = sql + c.getSqlString() + calledSql;
		sql = sql + " order by id desc";
		sql = pm.getMySQLPageSQL(sql, start, pageSize);
		
		List<Company> recordList = app.query(sql, Company.mapper, c.getValueList().toArray());
		
		pm.setPageNo(pageNo);
		pm.setPageSize(pageSize);
		pm.setRecordList(recordList);
		pm.setTotalRecord(getTotalRecord(c, calledSql));
		return pm;
	}
	
	protected List<Company> query(MoreCriteria c, String calledSql) {
		String sql = QUERY_DETAIL_SQL + c.getSqlString() + calledSql + " order by id desc";
		
		List<Company> recordList = app.query(sql, Company.mapper, c.getValueList().toArray());
		return recordList;
	}
	
	
	protected List<Map<String, Object>> loadNotes(int entId) {
		String sql = "SELECT notes, opt_user, gen_time FROM t_ent_sign_notes WHERE entId=?";
		return app.queryList(sql, entId);
	}
	
	/**
	 * 增加操作记录
	 * @param entId
	 * @param notes
	 * @param opt_user
	 */
	protected void addNotes(int entId, String notes, String opt_user) {
		app.update("INSERT INTO t_ent_sign_notes (entId, notes, opt_user)"
				+ " VALUES (?,?,?)", entId, notes, opt_user);
	}

	public boolean phoneCall(int id, String result, String opt_user) {
		String sql = "update t_ent_sign set phone_result=?, phone_time=now()"
				+ " where id=?";
		boolean ret = app.update(sql, result, id);
		if (ret) {
			addNotes(id, result, opt_user);
		}
		return ret;
	}
	
	protected boolean updateContact(int id, String wechat, String qq,
			String email, String opt_user) {
		StringBuilder notes = new StringBuilder();
		if (StringUtils.isNotBlank(wechat)) {
			notes.append(" 微信：" + wechat);
			app.update("update t_ent_sign set wechat=? where id=?", wechat, id);
		}
		if (StringUtils.isNotBlank(qq)) {
			notes.append(" QQ：" + qq);
			app.update("update t_ent_sign set qq=? where id=?", qq, id);
		}
		if (StringUtils.isNotBlank(email)) {
			notes.append(" 邮箱：" + email);
			app.update("update t_ent_sign set email=? where id=?", email, id);
		}
		if (notes.length() > 0) {
			addNotes(id, notes.toString(), opt_user);
		}
		return true;
	}
	

	protected boolean entSign(String city, String enName, String contact_name, 
			String contact_phone, String employees, String demand, 
			String remark, String opt_user, String sign_user) {
		short opt_sign = 1;
		StringBuilder msg = new StringBuilder("手动登记. ");
		if (!sign_user.equals(opt_user)) {
			opt_sign = 2;
			msg.append(sign_user + "转给" + opt_user );
		}
		String sql = "INSERT INTO t_ent_sign (enName, contact_name, contact_phone, "
				+ "demand, employees, city, "
				+ "remark, opt_user, opt_sign, "
				+ "gen_time) VALUES (?,?,?, ?,?,?, ?,?,?, now())";
		int entId = app.insert(sql, "id", enName, contact_name, contact_phone,
				demand, employees, city, 
				remark, opt_user, opt_sign);
		if (entId > 0) {
			addNotes(entId, msg.toString(), sign_user);
			return true;
		}
		return false;
	}
	
	public boolean delete(int id) {
		String sql = "DELETE FROM t_ent_sign where id=?";
		return app.update(sql, id);
	}
	
	protected String getPhone(int id) {
		return app.queryString("SELECT contact_phone FROM t_ent_sign WHERE id=?", id);
	}
	
	protected List<String> entUserNames() {
		return admin.queryForList("SELECT uname FROM t_ent_user", String.class);
	}
	
	protected List<Map<String, Object>> entUsers() {
		return admin.queryList("SELECT * FROM t_ent_user");
	}
	protected String getAreas(String name) {
		return admin.queryString("SELECT areas FROM t_ent_user WHERE uname=?", name);
	}
	
	protected boolean saveEntUser(String uname, String areas) {
		if (StringUtils.isBlank(areas)) {
			return admin.update("DELETE FROM t_ent_user WHERE uname=?", uname);
		}
		String sql = "INSERT INTO t_ent_user (uname, areas) VALUES (?,?) ON DUPLICATE KEY UPDATE areas=?";
		return admin.update(sql, uname, areas, areas);
	}
	
	/**
	 * 保存文件合同的数据
	 * @param entId
	 * @param fileName
	 * @param opt_user
	 * @return
	 */
	protected boolean saveContract(int entId, String fileName, String fileType, String opt_user) {
		Contract c = getContract(entId, fileName);
		boolean ret = false;
		if (null == c) {
			String sql = "INSERT INTO t_ent_contract (entId, fileName, fileType ) VALUES (?,?,?)";
			ret = admin.update(sql, entId, fileName, fileType);
			if (ret) {
				app.update("UPDATE t_ent_sign SET contract_num=contract_num+1 WHERE id=?", entId);
				addNotes(entId, "上传合同："+fileName, opt_user);
			}
			return ret;
		} else if (c.getWantDelete() == 1) {
			ret = admin.update("UPDATE t_ent_contract SET wantDelete=0 WHERE id=?", c.getId());
		} else {
			ret = true;
		}
		addNotes(entId, "重新上传合同："+fileName, opt_user);
		return ret;
	}
	
	protected Contract getContract(int entId, String fileName) {
		String sql = "SELECT * FROM t_ent_contract WHERE entId=? AND fileName=?";
		return admin.queryT(sql, Contract.mapper, entId, fileName);
	}
	protected Contract getContract(int id) {
		String sql = "SELECT * FROM t_ent_contract WHERE id=?";
		return admin.queryT(sql, Contract.mapper, id);
	}
	
	protected List<Contract> listContract(int entId) {
		String sql = "SELECT * FROM t_ent_contract WHERE entId=?";
		return admin.query(sql, Contract.mapper, entId);
	}
	
	protected int deleteContract(int id, String opt_user) {
		String sql = "SELECT * FROM t_ent_contract WHERE id=?";
		Contract c = admin.queryT(sql, Contract.mapper, id);
		if (null == c) {
			return 0;
		}
		sql = "UPDATE t_ent_contract SET wantDelete=1 WHERE id=?";
		boolean ret = admin.update(sql, id);
		if (ret) {
			addNotes(c.getEntId(), "标记删除："+c.getFileName(), opt_user);
		}
		return c.getEntId();
	}
	

	/**
	 * 有新的企业用户注册
	 * @return
	 */
	protected int hasEntpriseReg(String login_user, String date1, String date2) {
		String sql = "SELECT COUNT(id) FROM t_ent_sign WHERE opt_user=?"
				+ " AND DATE(gen_time) between ? AND ? AND phone_time IS NULL";
		return app.queryInt(sql, login_user, date1, date2);
	}

}
